package inglar.autotc.shared.db;

import java.io.Serializable;

public class Clients implements Serializable {
	
	private static final long serialVersionUID = 138253264090667689L;
	
	private String id = null;
	private String address = null;
	private String port = null;
	
	private static final String head = "clients@{";
	private static final String tail = "}@";
	private static final String fieldSeparator = "#";
	
	public Clients() {
		
	}
	
	public Clients(String string) {
		this();
		
		String functag = "Clients(String)";
		int numfields = 3;
		
		if(string == null) 
			throw new NullPointerException(functag + ": Argument 1 is null");
		
		string = string.trim();
		if(!string.startsWith(head) || !string.endsWith(tail)) 
			throw new IllegalArgumentException(functag + ": Argument 1 is not " +
					"wrapped with '" + head + "' and '" + tail + "'");
		
		string = string.substring(head.length(), string.indexOf(tail));
		
		String[] values = string.split(fieldSeparator);
		
		if(values.length != numfields) 
			throw new IllegalArgumentException(functag + ": The number of " +
					"fields is not " + numfields);
		
		try {
			this.setId(values[0]);
			this.setAddress(values[1]);
			this.setPort(values[2]);
		} catch(Throwable cause) {
			throw new IllegalArgumentException(functag + ": " + 
					cause.getMessage());
		}
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) throws IllegalArgumentException {
		try {
			this.id = (new Integer(id)).toString();
		} catch (NumberFormatException nfe) {
			throw new IllegalArgumentException("id must be an integer");
		}
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) throws IllegalArgumentException {
		if(address == null) throw new IllegalArgumentException("ip address must not be null");
		address = address.trim();
		if(address.isEmpty()) throw new IllegalArgumentException("ip address must not be empty");
		this.address = address;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) throws IllegalArgumentException {
		try {
			this.port = (new Integer(port)).toString();
		} catch (NumberFormatException nfe) {
			throw new IllegalArgumentException("port must be an integer");
		}
	}
	
	public String toString() {
		return head + 
				this.getId() + fieldSeparator + 
				this.getAddress() + fieldSeparator + 
				this.getPort() + 
				tail;
	}
	
	/**
	 * Used for testing.
	 */
	public static void main(String[] args) {
		System.out.println(Clients.class.getName());
		
		try {
			Clients c = new Clients("clients@{0#12.7.0.0.1#19337}@");
			System.out.println("id: " + c.getId());
			System.out.println("address: " + c.getAddress());
			System.out.println("port: " + c.getPort());
			System.out.println(c);
		} catch (Throwable caught) {
			caught.printStackTrace();
		}
	}

}
